import { useEffect, useState, useCallback } from 'react';
import CaptchaFormItem from '@/components/CaptchaFormItem'
import { useNavigate } from 'react-router-dom';
import { Form, Input, Select, Checkbox, Button, Row, Col, message } from 'antd';
import Cookies from 'js-cookie';
import { getCountryList, getIndustryList, getResearchList, userBind } from '@/service';

import styles from './index.module.scss';
import { useTranslation } from 'react-i18next';
import Policy from '../Policy'

export default () => {
    const { t, i18n } = useTranslation();
    const initState = () => ({
        isVisible: false,
        countryList: [],
        industryList: [],
        researchList: [],
        loading: false
    }),
        navigate = useNavigate(),
        [state, setState] = useState(initState);
    const [form] = Form.useForm(); // 创建表单实例
    const [stateOptions, setStateOptions] = useState([]);
    const [showState, setShowState] = useState(false);
    const [showPostal, setShowPostal] = useState(false);
    const [focusOptions, setFocusOptions] = useState([]);
    const [focusState, setShowFocus] = useState(false);
    const [showOther, setShowOther] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();
    const handleCountryChange = (value) => {
        const selectedItem = (state.countryList || []).find(item => item['country/region'] === value);
        if (selectedItem?.state?.length > 0) {
            setShowState(true);
            selectedItem.state.shift();
            setStateOptions(selectedItem.state);
        } else {
            setShowState(false);
            setStateOptions([]);
        }
        setShowPostal(!!selectedItem?.postalCode);
    };
    const handleResearchChange = (value) => {
        const selectedItem = (state.researchList || []).find(item => item['areaOfResearch'] === value);
        if (selectedItem?.researchFocus?.length > 0) {
            setShowFocus(true);
            selectedItem.researchFocus.shift();
            setFocusOptions(selectedItem.researchFocus);
        } else {
            setShowFocus(false);
            setFocusOptions([]);
        }
        setShowOther(selectedItem?.areaOfResearch == 'Other');
    };
    const acceptFn = useCallback(() => {
        Cookies.set('portal_cookiesAccepted', 'true');
        setState((o) => ({ ...o, isVisible: false }));
    }, []);

    const rejectFn = useCallback(() => {
        Cookies.set('portal_cookiesAccepted', 'false');
        setState((o) => ({ ...o, isVisible: false }));
    }, []);
    const hasAcceptedCookies = () => {
        const cookieValue = Cookies.get('portal_cookiesAccepted');
        return cookieValue === 'true' || cookieValue === 'false';
    }
    const getCountry = () => {
        getCountryList().then(res => {
            const { code, data } = res;
            if (code == 0) {
                data.shift();
                setState((o) => ({ ...o, countryList: data }));
            }
        })
    }
    const getIndustry = () => {
        try {
            getIndustryList().then(res => {
                const { code, data } = res;
                if (code == 0) {
                    data.shift();
                    setState((o) => ({ ...o, industryList: data }));
                }
            })
        } catch (error) {
        }
    }
    const getResearch = () => {
        getResearchList().then(res => {
            const { code, data } = res;
            if (code == 0) {
                data.shift();
                setState((o) => ({ ...o, researchList: data }));
            }
        })
    }
    const submitFn = async () => {
        try {
            const values = await form.validateFields();
            const params = {
                "firstName": values.firstName,
                "lastName": values.lastName,
                "email": values.email.trim(),
                "institution": values.institution,
                "country": values.country,
                "postalCode": values.postalCode || '',
                "state": values.state || '',
                "industry": values.industry,
                "areaOfResearch": values.areaOfResearch,
                "researchFocus": values.researchFocus || '',
                "remark": values.remark,
                'otherAreaOfResearch': values.otherArea0fResearch || '',
            }
            console.log('params', params);
            setState((prevState) => ({ ...prevState, loading: true }));
            const res = await userBind(values);
            const { code, message } = res || {};
            if (code === 0) {
                navigate('/login');
            } else {
                messageApi.open({
                    type: 'error',
                    content: message,
                });
            }
        } catch (error) {
            if (error?.message) {
                messageApi.open({
                    type: 'error',
                    content: error?.message,
                });
            }
        } finally {
            setState((prevState) => ({ ...prevState, loading: false }));
        }
    };
    useEffect(() => {
        getCountry();
        getIndustry();
        getResearch();
        setState((o) => ({ ...o, isVisible: !hasAcceptedCookies() }));
    }, [i18n.language]);
    return (
        <div className={styles['container']}>
            {state?.isVisible && <div className={styles.cookiePopup}>
                <p>{t('menu.support.privacy.title')} </p>
                <p>{t('menu.support.privacy.countent')}</p>
                <div className={styles.btnGroup}>
                    <button className={styles.rejectBtn} onClick={rejectFn}>{t('menu.support.privacy.rejectBtn')}</button>
                    <button className={styles.acceptBtn} onClick={acceptFn}>{t('menu.support.privacy.acceptBtn')}</button>
                </div>
            </div>}
            <div className={styles.supportBox}>
                <div className={styles.leftBox}>
                    <Policy />
                </div>
                <div className={styles.rightBox}>
                    <div className={styles.content}>
                        <h1 className={styles.cssh1n2}>{t('menu.support.privacy.form.title')}</h1>
                        <p className={styles.title}>{t('menu.support.privacy.form.tip')}
                        </p>
                        <Form
                            form={form}
                            layout="vertical"
                            className='custom-form-primary'
                        >
                            <Form.Item
                                name="postal"
                                style={{ marginBottom: 0 }}
                            >
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <Form.Item
                                            name="firstName"
                                            rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                                        >
                                            <Input placeholder={t('menu.support.privacy.form.firstName')} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            name="lastName"
                                            rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                                        >
                                            <Input placeholder={t('menu.support.privacy.form.lastName')} />
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form.Item>
                            <Form.Item
                                name="email"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Input placeholder={t('menu.support.privacy.form.email')} />
                            </Form.Item>
                            <Form.Item
                                name="institution"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Input placeholder={t('menu.support.privacy.form.institution')} />
                            </Form.Item>
                            <Form.Item name="country" rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}>
                                <Select
                                    onChange={handleCountryChange}
                                    placeholder={t('menu.support.privacy.form.country')}
                                    popupClassName="custom-dropdown"
                                    options={(state?.countryList || []).map((item, index) => ({
                                        value: item['country/region'],
                                        label: item['country/region'],
                                        key: index
                                    }))}
                                >
                                </Select>
                            </Form.Item>
                            {showState && <Form.Item
                                name="state"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Select placeholder={t('menu.support.privacy.form.state')}
                                    popupClassName="custom-dropdown"
                                    options={(stateOptions || []).map((item, index) => ({
                                        value: item,
                                        label: item,
                                        key: index
                                    }))}
                                >
                                </Select>
                            </Form.Item>}

                            {showPostal && <Form.Item
                                name="postalCode"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Input placeholder={t('menu.support.privacy.form.postal')} />
                            </Form.Item>}

                            <Form.Item
                                name="industry"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}

                            >
                                <Select popupClassName="custom-dropdown" placeholder={t('menu.support.privacy.form.industry')} options={(state?.industryList || []).map((item, index) => ({
                                    value: item,
                                    label: item,
                                    key: index
                                }))}>
                                </Select>
                            </Form.Item>
                            <Form.Item
                                name="areaOfResearch"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Select placeholder={t('menu.support.privacy.form.research')}
                                    onChange={handleResearchChange}
                                    popupClassName="custom-dropdown"
                                    options={(state?.researchList || []).map((item, index) => ({
                                        value: item['areaOfResearch'],
                                        label: item['areaOfResearch'],
                                        key: index
                                    }))}>
                                </Select>
                            </Form.Item>

                            {focusState && <Form.Item
                                name="researchFocus"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Select placeholder={t('menu.support.privacy.form.focus')}
                                    popupClassName="custom-dropdown" options={(focusOptions || []).map((item, index) => ({
                                        value: item,
                                        label: item,
                                        key: index
                                    }))}
                                >
                                </Select>
                            </Form.Item>}

                            {showOther && <Form.Item
                                name="otherArea0fResearch"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Input placeholder={t('menu.support.privacy.form.specify')} />
                            </Form.Item>}

                            <Form.Item
                                name="remark"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Input.TextArea style={{ resize: 'none', minHeight: 100, lineHeight: 'normal' }} placeholder={t('menu.support.privacy.form.help')} />
                            </Form.Item>

                            <Form.Item
                                name="isAgreeReceiveCommonication"
                                valuePropName="checked"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Checkbox>
                                    {t('menu.support.privacy.form.genomics')} <em>{t('menu.support.privacy.form.preferences')}</em>
                                </Checkbox>
                            </Form.Item>

                            <Form.Item
                                name="isAgreePolicy"
                                valuePropName="checked"
                                rules={[{ required: true, message: t('menu.support.privacy.form.required') }]}
                            >
                                <Checkbox>
                                    {t('menu.support.privacy.form.acknowledge')} <a rel="noopener noreferrer" target="_blank" href="/policy" className="css-k0f5v edy1dh10">{t('menu.support.privacy.form.privacy')}</a>.
                                </Checkbox>
                            </Form.Item>

                            <Form.Item>
                                <Button type="primary" loading={state?.loading} htmlType="submit" block style={{ height: '48px', fontWeight: '600', fontSize: '18px' }} onClick={submitFn}>
                                    {t('menu.support.privacy.form.submitBtn')}
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
            </div>
            {contextHolder}
        </div>
    );
}